package com.test.lock;

import java.util.concurrent.Semaphore;

public class SemaphoreDemo {

    public static void main(String[] args) {

        // Create a semaphore with 1 permit
        Semaphore semaphore = new Semaphore(1);

        // Thread1 tries to acquire the permit
        new Thread(() -> {
            try {
                semaphore.acquire();
                System.out.println("Thread1 acquired the permit");

                // Sleep to simulate processing
                Thread.sleep(1000);

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                // Release the permit
                semaphore.release();
                System.out.println("Thread1 released the permit");
            }
        }).start();

        // Thread2 tries to acquire the permit
        new Thread(() -> {
            try {
                semaphore.acquire();
                System.out.println("Thread2 acquired the permit");

                // Sleep to simulate processing
                Thread.sleep(1000);

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                // Release the permit
                semaphore.release();
                System.out.println("Thread2 released the permit");
            }
        }).start();

    }

}